package com.tanguy.user

import android.content.Context
import android.support.multidex.MultiDex
import cn.sinata.xldutils_kotlin.application.BaseApplication
import cn.sinata.xldutils_kotlin.utils.SPUtils
import com.tanguy.user.bean.User
import com.tanguy.user.net.socket.OkioSocket
import com.tanguy.user.net.socket.SocketManager
import com.tanguy.user.utlis.StackManager
import com.tanguy.user.utlis.extend.rxTimer
import io.reactivex.disposables.Disposable

/**
 * Created by dab on 2017/9/26 0026 14:31
 */
class App : BaseApplication() {
    override fun getSPName(): String {
        return "m_data"
    }

    companion object {
        lateinit var app: App
        fun get(): App = app
    }

    override fun attachBaseContext(base: Context?) {
        super.attachBaseContext(base)
        MultiDex.install(this)
    }

    override fun onCreate() {
        super.onCreate()
        app = this
        StackManager.initStackManager(app)
        initSocket()
    }

    /**
     *  登出用户
     */
    fun logOut() {
        app.user = User()
        app.isLogin = false
        SPUtils.instance()
                .put(Const.User.ID, 0)
                .put(Const.User.PHONE, "")
                .apply()
    }

    /**
     * 是否登录
     */
    var isLogin = false
    /**
     * 用户信息(保存在内存)
     */
    var user: User = User()
        set(value) {
            field = value
            isLogin = true
            if (value.userId > 0) {
                SPUtils.instance().put(Const.User.ID, value.userId)
                        .put(Const.User.PHONE, value.phone)
                        .apply()
            }
            SocketManager.ping()
        }

    ///////////////////////////////////////////////////////////////////
    //Socket相关
    private val okioSocket = OkioSocket()

    private fun initSocket() {
        okioSocket.apply {
            var rxTimerDisposable: Disposable? = null
            setOnConnectCallBack({ succeed, _, _ ->
                if (succeed) {
                    SocketManager.ping()
                    rxTimerDisposable = rxTimer(Const.SocketType.INTERVAL) {
                        SocketManager.ping()
                    }
                } else {
                    rxTimerDisposable?.dispose()
                }
            }
            )
        }
        okioSocket.setOnMessageChange { SocketManager.parseJson(it) }
    }

     fun sendMassage(sendMsg: String) {
        okioSocket.send(sendMsg)
    }

     fun connectSocket() {
        okioSocket.connect(Const.Api.SOCKET_SERVER, Const.Api.SOCKET_PORT)
    }

    /**
     * 取消连接
     */
     fun offSocket() {
        try {
            okioSocket.close()
        } catch (e: Exception) {

        }
    }

}